<?php
/**
 * 咨询师-咨询时段
 *
 * User: kaikaic
 * Date: 2018/12/7
 * Time: 0:09
 */

/**
 * 实现思路(2018-12-07)
 *
 * 1.咨询师可用咨询时段按周记录，生成一条数据，以咨询师ID+周一零点时间戳作为索引
 * 2.每天的时间段分为：上午，下午，晚上,以小时为单位，具体时间根据配置(开始时间)
 * 3.每周可以按照工作日，周末批量设置
 * 4.其他操作规则待定
 */

namespace service;

class DateService {

    // 上午：9点，10点，11点
    private $morning = array(9, 10, 11);

    // 下午 14点，15点，16点，17点
    private $afternoon = array(14, 15, 16, 17);

    // 晚上 19点，20点，21点
    private $night = array(19, 20, 21);

    /**
     * 初始化一周的时间段安排
     *
     * @param $week,从当前日期开始向后的周数,$week=0表示本周
     * @return Array
     */
    public function initWeekDate($week) {
        $week = intval($week);

        // 得到指定周的开始日期和结束日期
        $weekTime = strtotime("+ {$week} week");
        $week = $this->getWeekday($weekTime);

        $weekDate = array();
        for ($i=0; $i<7; $i++) {
            $weekDate[] = date("Y-m-d", strtotime("+{$i} day", strtotime($week[0])));
        }

        $timeRange = array();
        foreach ($weekDate as $value) {
            $morningArray = array();
            foreach ($this->morning as $val) {
                $temp = array();
                $temp['time'] = $val;
                $temp['timestamp'] = strtotime($value) + $val * 3600;
                $temp['date'] = date("Y-m-d H", $temp['timestamp']);
                $temp['book'] = 0;

                $morningArray[] = $temp;
            }
            $timeRange[$value]['morning'] = $morningArray;

            $afternoonArray = array();
            foreach ($this->afternoon as $val) {
                $temp = array();
                $temp['time'] = $val;
                $temp['timestamp'] = strtotime($value) + $val * 3600;
                $temp['date'] = date("Y-m-d H", $temp['timestamp']);
                $temp['book'] = 0;

                $afternoonArray[] = $temp;
            }
            $timeRange[$value]['afternoon'] = $afternoonArray;

            $nightArray = array();
            foreach ($this->night as $val) {
                $temp = array();
                $temp['time'] = $val;
                $temp['timestamp'] = strtotime($value) + $val * 3600;
                $temp['date'] = date("Y-m-d H", $temp['timestamp']);
                $temp['book'] = 0;

                $nightArray[] = $temp;
            }
            $timeRange[$value]['night'] = $nightArray;
        }

        // 以开始日期时间戳为标志，生成记录
        $params = array();
        $params['start_date'] = strtotime($week[0]);
        $params['time_range'] = serialize($timeRange);

        return $params;
    }

    private function getWeekday($time) {
        $time = empty($time) ? time() : $time;

        $w = date('w', $time);
        $w = $w ?  $w : 7;

        $month = date('m', $time);
        $day = date('d', $time);
        $year = date('Y', $time);

        $data[] = date('Y-m-d', mktime(0, 0, 0, $month, $day - $w + 1, $year));
        $data[] = date('Y-m-d', mktime(0, 0, 0, $month, $day + 7 - $w, $year));

        return $data;
    }
}